﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetConfig;
using LBSoft.Common.DotNetData;
using LBSoft.Common.DotNetEncrypt;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetFile;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace LBSoft.HplusAdmin.Business.UserInfoManage
{
    /// <summary>
    /// UserInfoManage 的摘要说明
    /// </summary>
    public class UserInfoManage : IHttpHandler
    {
        HttpContext con = null;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();
        LogHelper log = new LogHelper();

        public void ProcessRequest(HttpContext context)
        {
            con = context;

            switch (con.Request["PostType"])
            {
                case "list": LoadList(); break;
                case "get": GetData(); break;
                case "set": SetData(); break;
                case "del": DelData(); break;
            }
        }

        #region 列表
        private void LoadList()
        {
            switch (con.Request["ActionType"])
            {
                case "UserInfo": LoadUserInfoList(); break; //账号列表
            }
        }

        /// <summary>
        /// 账号列表
        /// </summary>
        private void LoadUserInfoList()
        {
            int count = 0;
            int pageSize = con.Request["rows"].ToInt32(15);
            int curPage = con.Request["page"].ToInt32(1);

            IList<SqlParam> IList_param = new List<SqlParam>();
            StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));
            SqlWhere.AppendFormat(" AND IsDelete=0");
            SqlWhere.AppendFormat(" AND UserType<>1"); //排除超级管理员

            string tables = @" SYS_UserInfo ";
            string cols = @" * ";
            string orderStr = " CreateDate Desc ";

            DataTable dt = systemidao.GetListByPage(tables, cols, SqlWhere, orderStr, IList_param, curPage, pageSize, ref count);

            json.success = true;
            json.total = count;
            json.rows = dt;

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 获取
        private void GetData()
        {
            switch (con.Request["ActionType"])
            {
                case "UserInfo": GetUserInfo(); break; //获取账号
            }
        }

        /// <summary>
        /// 获取账号
        /// </summary>
        private void GetUserInfo()
        {
            string guid = con.Request["GUID"].ToString2();

            Hashtable ht = systemidao.GetDataByID("SYS_UserInfo", "GUID", guid);
            ht["RoleName"] = string.Empty;

            string roleGUID = ht["RoleGUID"].ToString2();
            if (!string.IsNullOrEmpty(roleGUID))
            {
                string roleGUIDStr = roleGUID.Replace(",", "','");
                string RoleName = systemidao.ExecuteScalar($"SELECT STUFF((SELECT ',' + RoleName FROM SYS_Roles WHERE GUID IN ('{roleGUIDStr}') FOR XML PATH('')),1,1,'') RoleName").ToString2();
                ht["RoleName"] = RoleName;
            }

            con.Response.Write(JsonConvert.SerializeObject(ht));
        }
        #endregion

        #region  编辑
        private void SetData()
        {
            switch (con.Request["ActionType"])
            {
                case "UserInfo": SetUserInfo(); break; //账号保存
                case "ResetPwd": SetResetPwd(); break; //重置密码
                case "UpdatePwd": SetUpdatePwd(); break; //设置密码
            }
        }

        /// <summary>
        /// 账号保存
        /// </summary>
        private void SetUserInfo()
        {
            try
            {
                string userId = RequestSession.GetSessionUser().UserId;
                string userAccount = RequestSession.GetSessionUser().UserAccount;

                string guid = con.Request["GUID"].ToString2();
                string userAccountName = con.Request["UserAccount"].ToString2();

                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT GUID FROM dbo.SYS_UserInfo WHERE IsDelete=0 AND UserAccount='{userAccountName}' AND GUID!='{guid}'"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    json.msg = "账号已存在！";
                    con.Response.Write(JsonConvert.SerializeObject(json));
                    return;
                }

                Hashtable ht = systemidao.AddHashtable("SYS_UserInfo", con);

                if (string.IsNullOrEmpty(guid))
                {
                    ht["IsDelete"] = 0;
                    ht["CreateDate"] = DateTime.Now;
                    ht["CreateUserId"] = userId;
                    ht["CreateAccount"] = userAccount;

                    string DefaultPwd = ConfigHelper.GetAppSettings("DefaultPwd");
                    ht["UserPwd"] = Md5Helper.MD5(DefaultPwd, 32);
                }
                else
                {
                    ht.Remove("IsDelete");
                    ht.Remove("CreateDate");
                    ht.Remove("CreateUserId");
                    ht.Remove("CreateAccount");
                    ht.Remove("UserPwd");
                    ht["ModifyDate"] = DateTime.Now;
                    ht["ModifyUserId"] = userId;
                    ht["ModifyAccount"] = userAccount;
                }

                string htUserAccount = ht["UserAccount"].ToString2();
                string portraitUrl = con.Request["PortraitUrl"].ToString2();
                //上传的照片重新覆盖
                if (portraitUrl.IndexOf("PortraitPicturesTemp") != -1)
                {
                    string sourceFileName = HttpContext.Current.Server.MapPath(portraitUrl);
                    //图片后缀
                    int indexExt = portraitUrl.LastIndexOf('.');
                    string fileName = portraitUrl.Substring(indexExt);
                    string fileExt = Path.GetExtension(fileName).ToLower();
                    string newFileUrl = $"/PortraitPictures/{htUserAccount}{fileExt}";
                    string destFileName = HttpContext.Current.Server.MapPath(newFileUrl);

                    FileHelper.CopyFile(sourceFileName, destFileName, true);
                    ht["PortraitUrl"] = newFileUrl;
                }

                bool result = systemidao.SubmitData("SYS_UserInfo", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "保存成功！";
                }
                else
                {
                    json.msg = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        private void SetResetPwd()
        {
            try
            {
                string guid = con.Request["GUID"].ToString2();
                string defaultPwd = ConfigHelper.GetAppSettings("DefaultPwd");
                string md5DefaultPwd = Md5Helper.MD5(defaultPwd, 32);

                Hashtable ht = new Hashtable();
                ht["GUID"] = guid;
                ht["UserPwd"] = md5DefaultPwd;

                bool result = systemidao.SubmitData("SYS_UserInfo", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "重置成功！";
                }
                else
                {
                    json.msg = "重置失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 设置密码
        /// </summary>
        private void SetUpdatePwd()
        {
            try
            {
                string guid = con.Request["GUID"].ToString2();
                string userPwd = con.Request["UserPwd"].ToString2();
                string md5UserPwd = Md5Helper.MD5(userPwd, 32);

                Hashtable ht = new Hashtable();
                ht["GUID"] = guid;
                ht["UserPwd"] = md5UserPwd;

                bool result = systemidao.SubmitData("SYS_UserInfo", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "设置成功！";
                }
                else
                {
                    json.msg = "设置失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 删除
        private void DelData()
        {
            switch (con.Request["ActionType"])
            {
                case "UserInfo": DelUserInfo(); break; //账号删除
            }
        }

        /// <summary>
        /// 账号删除
        /// </summary>
        private void DelUserInfo()
        {
            string guid = con.Request["GUID"].ToString2();

            if (string.IsNullOrEmpty(guid))
            {
                json.success = false;
                json.msg = "没有要删除的主键！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            List<string> list = guid.Split(',').ToList<string>();
            bool result = systemidao.BatchUpdateDeleteData("SYS_UserInfo", "GUID", list.ToArray()) > 0;
            json.success = result;

            if (result)
            {
                json.msg = "删除成功！";
            }
            else
            {
                json.msg = "删除失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}